package helpers;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Vector;

import objects.Domino;
import objects.Player;

public class DominoesSorter {

	public Vector <Player> players;
	int setSize =16;
	public Vector<Domino> gameSet;
	
	public DominoesSorter(Vector<Player> players, Vector<Domino> gameSet){
		this.players = players;
		this.gameSet = gameSet;	
	}
	
	public  void sortDominoes(){
		
		switch (players.size()){
		case 2 : setSize=16; break;
		case 3 : setSize = 16;break;
		case 4 : setSize = 15;break;
		case 5 : setSize = 14;break;
		case 6 : setSize = 12;break;
		case 7 : setSize = 10;break;
		case 8 : setSize = 9;
		}
		
		System.out.println("giving dominoes to "+players.size()+" players.");
		for(Player p : players){
			Vector <Domino> playerSet = new Vector <Domino>();
			getRandomDominoes(playerSet, gameSet);
			p.setDominoSet(playerSet);				
		}
		
	}

	private void getRandomDominoes(Vector<Domino> playerSet, Vector<Domino> gameSet) {
		
		for(int i = 0 ; i < setSize; i++){
			Domino domino = getRandomDomino(playerSet, gameSet);
			playerSet.add(domino);
			gameSet.remove(domino);
			Domino sister = Domino.findDomino(domino.getSecond(), domino.getFirst());
			gameSet.remove(sister);
		}
		
	}

	public Domino getRandomDomino(Vector<Domino> playerSet, Vector<Domino> gameSet) {
		 Random randomer  =new Random();
		 int randomNumber = randomer.nextInt( Math.abs(gameSet.size()));
		 
		 Domino domino = gameSet.get(randomNumber);
		 
		 while(playerSet.contains(domino)){
			 randomNumber = randomer.nextInt(gameSet.size());
			 domino = gameSet.get(randomNumber);
		 }
		 
		 return domino;
		 
	}
	
	private void printPlayerSets() {
		
		for(Player p : players){
			System.out.println("Player:"+ players.indexOf(p)+" ");
			for(Domino d : p.getDominoSet()){
				
				System.out.print("["+d.getFirst()+","+d.getSecond()+"]");
				
			}
			System.out.println("");
			
		}
		
	}
	
	public static void main(String args[]){
		
		Player player1 = new Player();
		Player player2 = new Player();
		
//		Vector<Player> players = new Vector<Player>();
//		players.add(player1);
//		players.add(player2);
//		DominoesSorter sorter =  new DominoesSorter();
//		sorter.players= players;
//		
//		sorter.sortDominoes();
//		System.out.println("END");
//		sorter.printPlayerSets();
		
	}

	
	
}
